﻿using System;
using System.Net;
using Microsoft.Office.Project.Server.Library;

namespace MSPE.Public.FOSS.AutoStatusPlus.TimerJob
{
    /// <summary>
    /// Perfom WS impersonation
    /// </summary>
    internal class StatusingDerived : StatusingSvc.Statusing
    {
        private String _contextString = String.Empty;

        protected override WebRequest GetWebRequest(Uri uri)
        {
            //here we are overriding the GetWebRequest method and adding the 2 web request headers
            WebRequest _webRequest = base.GetWebRequest(uri);
            if (_contextString != String.Empty)
            {
                _webRequest.UseDefaultCredentials = true;
                _webRequest.Credentials = CredentialCache.DefaultCredentials;
                _webRequest.Headers.Add("PjAuth", _contextString);
                _webRequest.Headers.Add("ForwardFrom", "/_vti_bin/psi/statusing.asmx");
                _webRequest.PreAuthenticate = true;
            }
            return _webRequest;
        }

        public void SetImpersonationContext(bool isWindowsUser, String userNTAccount, Guid userGuid, Guid trackingGuid, Guid siteId, String lcid)
        {
            _contextString = GetImpersonationContext(isWindowsUser, userNTAccount, userGuid, trackingGuid, siteId, lcid);
        }

        private String GetImpersonationContext(bool isWindowsUser, String userNTAccount, Guid userGuid, Guid trackingGuid, Guid siteId, String lcid)
        {
            PSContextInfo _contextInfo = new PSContextInfo(isWindowsUser, userNTAccount, userGuid, trackingGuid, siteId, lcid);
            return PSContextInfo.SerializeToString(_contextInfo);
        }
    }
}
